<template>
  <div class="page-container">
    <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="dynamicForm1" />
    <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons">
      <template #code="{ text, record }">
        <span class="text-blue-400 cursor-pointer" @click="handleShow(record)">{{ text }}</span>
      </template>
    </DynamicTable>
  </div>
  <ViewDialog v-model:visible="state.showDetail" v-if="state.showDetail" :data="state.showData" :show-type="state.showType" @handleEdit="handleEdit" />
  <PreviewDialog v-model:visible="state.showPreview" v-if="state.showPreview" :data="state.showPreviewData" />
  <div style="display: none">
    <PrintFileList :list="state.showList" />
    <PrintInList :list="state.showList" :pages="state.inListPages" />
    <PrintCoverList :list="state.showList" />
    <PrintBackList :list="state.showList" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onBeforeUnmount, nextTick } from 'vue';
import { DynamicForm } from '@/components/public-template';
import { DynamicTable } from '@/components/public-template';
import { DYNAMICLAYERFORM, DYNAMICLOCALICONS, DYNAMICLOCALTABLE, LOCALSUBSERVE } from '@/mixins/subject/subject-types';
import { filter } from 'rxjs/operators';
import { Api, boxGet, boxPrintArchivesBoxDirectory, boxPrintBoxWithInDirectory, boxPrintCoverOrSpine } from '@/config/api/archives';
import ViewDialog from './components/viewDialog.vue';
import PreviewDialog from './components/previewDialog.vue';
import PrintFileList from './components/printFileList.vue';
import PrintInList from './components/printInList.vue';
import PrintCoverList from './components/printCoverList.vue';
import PrintBackList from './components/printBackList.vue';
import indexService from './index.service';
import { CODE_RULE, generateCode } from '@/config/api/authorityManage';
import html2canvas from 'html2canvas';
import { message } from 'ant-design-vue';
import printJS from 'print-js';
import printStyles from '@/assets/style/print.less?inline';

const state = reactive({
  showData: null,
  showDetail: false,
  showType: null,
  showPreview: false,
  showPreviewData: null,
  showList: [],
  inListPages: 1
});
const dyConfig: any = {
  name: 'boxDist',
  labelCol: 6,
  wrapperCol: 18,
  grid: 8, //分栏
  style: 'table-form',
  cancelSave: true //隐藏底部按钮
};
const dyTableConfig: any = {
  name: 'boxDist',
  queryUrl: Api.boxPage,
  protType: 'post',
  isScreen: true,
  rowSelection: {
    type: 'checkbox'
  }
};
const dyPrintConfig: any = {
  name: 'printDist',
  title: '打印类型',
  width: '390px',
  type: 'layer',
  labelCol: 8,
  wrapperCol: 24,
  grid: 24,
  layout: 'vertical',
  okText: '打印',
  localSub: true
};
const dyQuestions: any = reactive(indexService.getQuestions());
const dyPrintQuestions: any = reactive(indexService.getPrintQuestions());
const dyTable: any = reactive(indexService.getTables());
const dyIcons: any = reactive(indexService.getIcons());
//监听table
const { proxy }: any = getCurrentInstance();
const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === DYNAMICLOCALICONS) {
      const { value } = item;
      switch (value.state.type) {
        case 'PRINT_FILE_LIST':
          printFileList(item.state.selected);
          break;
        case 'PRINT_COVER_DIRECTORY':
          printInList(item.state.selected);
          break;
        case 'PRINT_COVER':
          printCoverList(item.state.selected);
          break;
        case 'PRINT_BACK':
          printBackList(item.state.selected);
          break;
        case 'BOX_ADD':
          handleAdd();
          break;
        default:
          break;
      }
    } else if (item.key === DYNAMICLOCALTABLE) {
      state.showPreview = true;
      state.showPreviewData = item.value.data;
    }
  });
const subscribeSubForm = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === LOCALSUBSERVE && item.state.name == dyPrintConfig.name) {
      const params = { ids: item.value.ids };
      boxPrintCoverOrSpine(params).then((res) => {
        if (res.success) {
          state.showList = res.data;
          nextTick(() => {
            print('printBackList', item.value.spineThickness);
          });
        }
      });
    }
  });

// 添加档案盒
function handleAdd() {
  const params = { type: CODE_RULE.DAHBM };
  generateCode(params).then((res) => {
    let boxCode;
    if (res.success && res.data.length) boxCode = res.data[0];
    state.showType = 'ADD';
    state.showDetail = true;
    state.showData = { code: boxCode };
  });
}

// 档案盒详情
function handleShow(record) {
  boxGet(record.id).then((result) => {
    if (result.success) {
      state.showType = 'VIEW';
      state.showDetail = true;
      state.showData = result.data;
    }
  });
}
// 档案盒编辑
function handleEdit(data) {
  state.showDetail = false;
  nextTick(() => {
    state.showType = 'EDIT';
    state.showDetail = true;
    state.showData = data;
  });
}
// 打印卷内目录
function printFileList(record) {
  if (!record.length) return message.warning('请先选中一个选项');
  const params = { ids: record.map((item) => item.id) };
  boxPrintBoxWithInDirectory(params).then((res) => {
    if (res.success) {
      state.showList = res.data.map((item) => item.list);
      nextTick(() => {
        print('printFileList');
      });
    }
  });
}
// 打印案卷目录
function printInList(record) {
  if (!record.length) return message.warning('请先选中一个选项');
  const params = { ids: record.map((item) => item.id) };
  boxPrintArchivesBoxDirectory(params).then((res) => {
    if (res.success) {
      state.showList = allocationArray(res.data);
      state.inListPages = Math.floor(res.data.length / 15) + 1;
      nextTick(() => {
        print('printInList');
      });
    }
  });
}
// 计算案卷目录的页数
function allocationArray(arr) {
  if (arr.length <= 15) return [arr];
  const subarray = [];
  let count = Math.ceil(arr.length) / 15;
  for (let i = 0; i < count; i++) {
    subarray.push(arr.slice(i * 15, (i + 1) * 15));
  }
  return subarray;
}
// 打印封面
function printCoverList(record) {
  if (!record.length) return message.warning('请先选中一个选项');
  const params = { ids: record.map((item) => item.id) };
  boxPrintCoverOrSpine(params).then((res) => {
    if (res.success) {
      state.showList = res.data;
      nextTick(() => {
        print('printCoverList');
      });
    }
  });
}
// 打印背脊
function printBackList(record) {
  if (!record.length) return message.warning('请先选中一个选项');
  dyPrintConfig.data = { ids: record.map((item) => item.id), spineThickness: 20 };
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERFORM,
    value: {
      config: dyPrintConfig,
      form: dyPrintQuestions,
      name: 'signatureForm'
    }
  });
}

async function print(printId, spineThickness = '20') {
  if (!printId) return;
  const style = printStyles.replaceAll('20mm', `${spineThickness}mm`);
  printJS({
    printable: printId, // 你要打印的内容的id或class
    type: 'html',
    style,
    scanStyles: false, // 库将不会处理应用于正在打印的html的样式
    onPrintDialogClose: () => {
      // 打印对话框关闭时执行的操作
      // 这里可以处理打印完成后的逻辑
    }
  });
}

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  subscribeSubForm && subscribeSubForm.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
  proxy.$NotificationFormSub.clearParams();
});
</script>

<style lang="less" scoped></style>
